package cn.jiaqiang.chatgpt.data.types.shadowsocks;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AESUtil {

    // AES加密算法名称
    private static final String ALGORITHM = "AES";
    // 加密模式
    private static final String MODE = "AES/CFB/PKCS5Padding";
    // IV偏移量，长度必须为16字节
    private static final String IV = "1234567890123456";
    private static final String key = "0123456789abcdef0123456789abcdef";

    // 加密方法
    public static String encrypt( String data) throws Exception {
        Cipher cipher = Cipher.getInstance(MODE);
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] encrypted = cipher.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(encrypted);
    }

    // 解密方法
    public static String decrypt( String encryptedData) throws Exception {
        Cipher cipher = Cipher.getInstance(MODE);
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        return new String(decrypted);
    }

    public static void main(String[] args) throws Exception {
        // 测试数据
        String key = "0123456789abcdef0123456789abcdef"; // 256位密钥
        String data = "Hello, AES!";
        
        // 加密
        String encrypted = encrypt(data);
        System.out.println("加密后的数据：" + encrypted);

        // 解密
        String decrypted = decrypt(encrypted);
        System.out.println("解密后的数据：" + decrypted);
    }
}